<script lang="ts" setup>
import { Emotion, RecommendReply, RecommendStatus } from '@/models/recommend'
import { Status } from '@/models/sys'
import { regenerateSubmit } from '@/service/index/recommend'
import { avatarUrl, awaitTo } from '@/utils'
import _ from 'lodash'

const props = withDefaults(
  defineProps<{
    itemData: RecommendReply
    status: RecommendStatus
  }>(),
  {},
)

const overTextOpen = ref(false)
const overAiTextOpen = ref(false)
const textOver = useTextOverflow(2)
const textAiOver = useTextOverflow(3)
onMounted(() => {
  textOver.textOver(props.itemData.content)
  textAiOver.textOver(props.itemData.reply_content)
})

const tagStatus = computed(() => {
  if (props.itemData.emotion === Emotion.SuspectedPositive) {
    return 'tag-green'
  } else if (props.itemData.emotion === Emotion.Negative) {
    return 'tag-red'
  } else {
    return 'tag-blue'
  }
})

const emit = defineEmits([
  'feedback',
  'suspectedPositive',
  'openChat',
  'sendMessage',
  'bad',
  'editReply',
  'streamDone',
])
/** 采集好评跳转 */
function suspectedPositiveClick() {
  emit('suspectedPositive')
}

const inputValue = ref(_.cloneDeep(props.itemData.reply_content || ''))

function isRegenerateCallback(callback: () => void) {
  if (isRegenerate.value) {
    uni.showToast({
      title: 'AI结果生成中，请耐心等待~',
      icon: 'none',
    })
    return
  }
  callback()
}

const copyClick = () => {
  uni.setClipboardData({
    data: props.itemData.reply_content,
    success() {
      uni.showToast({
        title: '复制成功',
        icon: 'none',
      })
    },
  })
}

const isRegenerate = ref(false)
/** 重新生成 */
async function regenerate() {
  if (isRegenerate.value) return
  isRegenerate.value = true
  inputValue.value = undefined
  textAiOver.init(`textContent_${props.itemData.id}_ai`)
  overAiTextOpen.value = true
  // emit('updateMessage', { ...props.itemData, reply_content: '' })
  const { result } = await awaitTo(
    regenerateSubmit({
      id: props.itemData.id,
      protocol: 'http',
    }),
  )
  uni.hideLoading()

  if (result.data) {
    inputValue.value = result.data.content
    isRegenerate.value = false
    uni.showToast({
      title: '生成成功',
      icon: 'none',
    })
  }
  // regenerateRecommendReply(
  //   { id: props.itemData.id },
  //   (msg) => {
  //     isRegenerate.value = true
  //     inputValue.value += msg
  //   },
  //   () => {
  //     isRegenerate.value = false
  //   },
  // )
}

const isEdit = ref(false)
const isFocus = ref(false)
const textareaRef = ref()
/** 编辑 */
const openEdit = () => {
  isEdit.value = !isEdit.value
  // 获取焦点
  if (isEdit.value) {
    isFocus.value = true
  } else {
    isFocus.value = false
  }

  if (!isEdit.value) {
    emit('editReply', { id: props.itemData.id, reply_content: inputValue.value })
  }
}
/** 失去焦点 */
const inputBlur = () => {
  isFocus.value = false
  isEdit.value = false
  emit('editReply', { id: props.itemData.id, reply_content: inputValue.value, blur: true })
}

const sedMessage = () => {
  emit('sendMessage', { id: props.itemData.id, reply_content: inputValue.value })
}

const toggleText = () => {
  if (!textOver.isTextOverflow.value) return
  overTextOpen.value = !overTextOpen.value
}

const isPending = computed(() => {
  return props.itemData.status === RecommendStatus.Pending
})
</script>

<template>
  <view class="list-view">
    <view class="head">
      <view class="flex items-center" style="width: 100%">
        <image :src="avatarUrl(itemData.customer.avatar)" class="avatar"></image>
        <view
          class="name"
          :style="itemData.emotion !== Emotion.Unknown ? 'max-width: calc(100% - 240rpx)' : ''"
        >
          {{ itemData.customer.display_name }}
        </view>
        <view :class="tagStatus" v-if="itemData.emotion !== Emotion.Unknown">
          {{ itemData.emotion_label }}
        </view>
      </view>
      <view
        v-if="itemData.emotion === Emotion.SuspectedPositive"
        class="status-tag"
        @click="suspectedPositiveClick"
      >
        采集好评
      </view>
    </view>
    <!-- 超出文本显示 -->
    <view class="user-chat" @click="isRegenerateCallback(toggleText)">
      <view
        style="flex: 1; font-size: 28rpx; text-align: justify"
        :id="`textContent_${itemData.id}`"
        :class="textOver.isTextOverflow.value && !overTextOpen ? 'ellipsis-2' : ''"
      >
        {{ itemData.content }}
      </view>
      <view style="height: 35rpx" v-if="overTextOpen"></view>

      <view v-if="textOver.isTextOverflow.value" class="arrow-view">
        <text v-if="!overTextOpen">...</text>
        <view
          class="arrow-down"
          :style="overTextOpen ? 'transform: rotate(180deg); bottom: 10rpx' : ''"
        ></view>
      </view>
    </view>
    <view class="ai-view">
      <view class="flex items-center">
        <image src="@/static/images/sys/ai-logo.png" class="logo"></image>
        <view class="desc">田博士-推荐回复</view>
      </view>
      <view class="tips" @click="$emit('feedback')">AI有错误？</view>
    </view>
    <!-- 待回复 -->
    <view class="edit-input" v-if="isPending" :style="isFocus ? 'border: 2rpx solid #1876ff' : ''">
      <textarea
        v-if="isEdit"
        ref="textareaRef"
        auto-height
        v-model="inputValue"
        :disabled="!isEdit"
        :focus="isFocus"
        :maxlength="5000"
        style="font-size: 28rpx; line-height: 34rpx; color: #1f2d47"
        @focus="() => (isFocus = true)"
        @blur="() => isRegenerateCallback(inputBlur)"
        :placeholder="isRegenerate ? '生成中' : '请输入'"
      ></textarea>
      <view v-else style="font-size: 28rpx; color: #1f2d47; white-space: pre-line">
        {{ isRegenerate ? inputValue || '生成中...' : inputValue || '暂无数据' }}
      </view>
      <view class="icons" v-if="!isRegenerate">
        <view class="edit-icon-btn" @click="isRegenerateCallback(openEdit)"></view>
      </view>
    </view>
    <!-- 已回复 -->
    <view class="edit-input" @click="overAiTextOpen = !overAiTextOpen" v-if="!isPending">
      <view
        :id="`textContent_${itemData.id}_ai`"
        style="font-size: 28rpx"
        :class="textAiOver.isTextOverflow.value && !overAiTextOpen ? 'ellipsis-2' : ''"
      >
        {{ inputValue || '暂无数据' }}
      </view>
      <view style="height: 35rpx" v-if="overAiTextOpen"></view>
      <view v-if="textAiOver.isTextOverflow.value && !isRegenerate" class="arrow-view">
        <text v-if="!overAiTextOpen">...</text>
        <view
          class="arrow-down"
          :style="overAiTextOpen ? 'transform: rotate(180deg); bottom: 10rpx' : ''"
        ></view>
      </view>
    </view>
    <view class="flex items-center justify-between mt-3">
      <view class="flex items-center">
        <view class="copy-btn mr-2" @click="isRegenerateCallback(copyClick)"></view>
        <view
          class="refresh-btn mr-2"
          @click="regenerate"
          v-if="status !== RecommendStatus.Sent"
        ></view>
        <view
          class="like-btn mr-2"
          :class="itemData.is_bad === Status.Yes && 'active-like-icon'"
          @click="$emit('bad')"
        ></view>
      </view>

      <view class="flex items-center">
        <view class="btn" @click="$emit('openChat')">打开对话</view>
        <view class="btn ml-3" v-if="isPending" @click="isRegenerateCallback(sedMessage)">
          立即发送
        </view>
        <view class="is-send-btn ml-3" v-else>已发送</view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.is-send-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 152rpx;
  height: 60rpx;
  font-size: 28rpx;
  font-weight: 500;
  color: #9fa3aa;
  background: #f8f9fb;
  border-radius: 30rpx;
}
.btn {
  box-sizing: border-box;
  padding: 10rpx 20rpx;
  font-family:
    PingFangSC,
    PingFang SC;
  font-size: 28rpx;
  font-weight: 500;
  color: #2b2f36;
  background: linear-gradient(85deg, #fcff5e 0%, #cfff69 49%, #6efffd 100%), #ffdb00;
  border-radius: 30rpx;
}
.btn:active {
  opacity: 0.8;
}
@mixin btn-center($url) {
  width: 60rpx;
  height: 60rpx;
  background: url($url) no-repeat;
  background-size: 100% 100%;

  &:active {
    border-radius: 50%;
    opacity: 0.5;
  }
}
.copy-btn {
  @include btn-center('@/static/images/index/copy-icon.png');
}
.refresh-btn {
  @include btn-center('@/static/images/index/refresh-icon.png');
}
.like-btn {
  @include btn-center('@/static/images/index/like-icon.png');
}

.active-like-icon {
  @include btn-center('@/static/images/index/active-like-icon.png');
}
.edit-input {
  position: relative;
  box-sizing: border-box;
  min-height: 124rpx;
  padding: 24rpx;
  color: #1f2d47;
  text-align: justify;
  border: 2rpx solid #dddddd;
  border-radius: 16rpx;
  textarea {
    width: 100%;
    min-height: 124rpx;
    font-size: 28rpx;
  }
  .icons {
    display: flex;
    justify-content: flex-end;
  }
}
.ai-view {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100rpx;
  .logo {
    width: 60rpx;
    height: 60rpx;
  }
  .desc {
    margin-left: 24rpx;
    font-family:
      PingFangSC,
      PingFang SC;
    font-size: 28rpx;
    font-weight: 400;
    color: #6a707c;
  }
  .tips {
    font-family:
      PingFangSC,
      PingFang SC;
    font-size: 26rpx;
    font-weight: 400;
    color: #1876ff;
  }
}
.user-chat {
  position: relative;
  box-sizing: border-box;
  padding: 24rpx;
  margin-top: 16rpx;
  overflow: hidden;
  line-height: 42rpx;
  color: #1f2d47;
  text-align: justify;
  border: 2rpx solid #dddddd;
  border-radius: 16rpx;
  .box-height {
    height: 30rpx;
  }
}
.arrow-view {
  position: absolute;
  right: 25rpx;
  bottom: 23rpx;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 79rpx;
  height: 45rpx;
  background-color: #ffffff;
}
.arrow-down {
  display: inline-block;
  width: 40rpx;
  height: 40rpx;
  margin-bottom: -2rpx;
  background: url('@/static/images/sys/arrow-down.png') no-repeat;
  background-color: #ffffff;
  background-size: 100% 100%;
}
@mixin flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40rpx;
  padding: 0 8rpx;
  font-family:
    PingFangSC,
    PingFang SC;
  font-size: 22rpx;
  font-weight: 400;
  color: #2b2f36;
  border-radius: 8rpx;
}
.list-view {
  box-sizing: border-box;
  min-height: 530rpx;
  padding: 32rpx;
  margin: 0 32rpx 24rpx 32rpx;
  background: #ffffff;
  border: 1rpx solid #2b2f36;
  border-radius: 24rpx;
  .head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .status-tag {
      box-sizing: border-box;
      height: 60rpx;
      padding: 8rpx 20rpx;
      font-family:
        PingFangSC,
        PingFang SC;
      font-size: 28rpx;
      font-weight: 500;
      color: #2b2f36;
      white-space: nowrap;
      background: #f8f9fb;
      border-radius: 30rpx;
    }
    .avatar {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
    }
    .name {
      max-width: calc(100% - 250rpx);
      margin-right: 24rpx;
      margin-left: 24rpx;
      font-family:
        PingFangSC,
        PingFang SC;
      font-size: 28rpx;
      font-weight: 400;
      color: #6a707c;
    }

    .tag-red {
      @include flex-center;
      background: #ffefef;
      border: 2rpx solid #dc5e5e;
    }

    .tag-green {
      @include flex-center;
      background: #eeffe8;
      border: 2rpx solid #87e363;
    }

    .tag-blue {
      @include flex-center;
      background: #edffff;
      border: 2rpx solid #88dbdd;
    }
  }
}
</style>
